package com.hue.gulimail.gulimailproduct.service.impl;

import com.hue.gulimail.gulimailproduct.entity.CategoryBrandRelationEntity;
import com.hue.gulimail.gulimailproduct.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hue.common.utils.PageUtils;
import com.hue.common.utils.Query;

import com.hue.gulimail.gulimailproduct.dao.BrandDao;
import com.hue.gulimail.gulimailproduct.entity.BrandEntity;
import com.hue.gulimail.gulimailproduct.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


/**
 * @author yfq
 */
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            wrapper.like("name", key).or().like("descript", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 修改品牌信息,同时修改其他表中的品牌信息
     *
     * @param brand
     */
    @Override
    @Transactional
    public void updateDetailById(BrandEntity brand) {
        //修改品牌表
        updateById(brand);
        //修改品牌分类关联表,保证冗余字段的一致
        //1.查询所有包含了这个品牌的关联关系
        QueryWrapper<CategoryBrandRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id", brand.getBrandId());
        List<CategoryBrandRelationEntity> categoryBrandRelationList = categoryBrandRelationService.list(wrapper);
        //将品牌名重新赋值
        for (CategoryBrandRelationEntity categoryBrandRelationEntity : categoryBrandRelationList) {
            categoryBrandRelationEntity.setBrandName(brand.getName());
        }
        //修改品牌名
        categoryBrandRelationService.updateBatchById(categoryBrandRelationList);
    }

}
